package command

import (
	"pan/api"
	"pan/common/conf"
	"pan/common/log"
)

type RefreshTokenCommand struct {
	expiresType int
}

func (r *RefreshTokenCommand) Run(opts []*Option, args []string) {
	if !r.parseOption(opts) {
		return
	}

	if !conf.IsTokenValid() {
		panic("token is invalid, you must login first")
	}

	req := &api.RefreshTokenRequest{
		ExpiresType: r.expiresType,
		Tokenid:     conf.GlobalToken.Tokenid,
		Userid:      conf.GlobalToken.Userid,
	}

	_, err := api.RefreshTokenApi(conf.GlobalToken.Tokenid, req)
	if err != nil {
		panic(err)
	}
	log.Info("refresh token success")
}

func (r *RefreshTokenCommand) parseOption(opts []*Option) bool {
	for _, opt := range opts {
		switch opt.Name {
		case "expires":
			r.expiresType = opt.IntValue
		}
	}
	if r.expiresType < 1 || r.expiresType > 2 {
		log.Error("expires type is invalid")
		return false
	}
	return true
}

func (r *RefreshTokenCommand) Arguments() []Argument {
	return nil
}

func (r *RefreshTokenCommand) Options() []*Option {
	return []*Option{
		{
			ShortName:    "e",
			Name:         "expires",
			Description:  "refresh token expires type: 1-three days, 2-one year",
			OptType:      IntOption,
			DefaultValue: 0,
		},
	}
}

func (r *RefreshTokenCommand) Description() string {
	return "Refresh token expires"
}

func NewRefreshTokenCommand() *RefreshTokenCommand {
	return &RefreshTokenCommand{}
}
